<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
     <!-- 引入Vue 全局注册一个名为Vue的构造函数 -->
 <script src="./js/vue.js"></script>
    <title>收集表单数据</title>
</head>
<!-- v-model修饰符 .number  .lazy  .trim -->
<body>
   <div id="root1">
    <form>
        <label for="demo">账号:</label>
        <input type="text" id="demo" v-model.trim="userInfo.account"><br><br>
        密码：<input type="password" v-model.trim="userInfo.password"><br><br>
        年龄:<input type="number"  v-model.number="userInfo.age"><br><br>
        名称:<input type="text"  v-model="userInfo.name" @input="checkLength"><br><br>
        性别:
        <input type="radio" value="0" name="sex" v-model="userInfo.sex"> 男
        <input type="radio" value="1" name="sex" v-model="userInfo.sex" >女  <br><br>

        爱好:
        <input type="checkbox" value="0" name="hobby" v-model="userInfo.hobby">乒乓球
        <input type="checkbox" value="1" name="hobby" v-model="userInfo.hobby">篮球
        <input type="checkbox" value="2" name="hobby" v-model="userInfo.hobby">羽毛球<br><br>
        所属校区:
        <select v-model="userInfo.location">
            <option value="0">请选择校区</option>
            <option value="1">东校区</option>
            <option value="2">北校区</option>
            <option value="3">南校区</option>
        </select><br><br>
        其他信息:<textarea v-model.lazy="userInfo.ainformation"></textarea><br><br>
        <input v-model="userInfo.agree" type="checkbox" >阅读并接受<a href="www.baidu.com">《用户协议》</a>
        <button @click="submitForm">提交</button>
    </form>
   </div> 

   <script>

     new Vue({
     el: '#root1',
     data: {
        userInfo:{
      name:'',
      age:0,
      account:"",
      password:'',
      sex:'',
      hobby:[],
      location:'',
      ainformation:'',
      agree:''
        }
     },
     methods:{
        submitForm(){
         alert('提交成功'),
         console.log(JSON.stringify(this.userInfo));
        },
        checkLength(){
         let value = this.userInfo.name;
         let byteLength = new TextEncoder().encode(value).length;
         console.log('length',byteLength);
         if(byteLength > 32 && value.length > 0){
          value = value.slice(0, -1); // 移除最后一个字符
         }
         this.userInfo.name = value;
        }
     }
     }
     )
   </script>
</body>
</html>